#!/usr/bin/env python
#
# Copyright 2015 Grand Share team (NSC2015).
#
FACEBOOK_APP_ID = "284029084983683"
FACEBOOK_APP_SECRET = "44dc226084ecc9c2a40213189e0573db"

import facebook
import webapp2
import os
import jinja2
import logging
from accounts import *

from google.appengine.ext import db
from webapp2_extras import sessions

config = {}
config['webapp2_extras.sessions'] = dict(secret_key='')


class BaseHandler(webapp2.RequestHandler):
    """Provides access to the active Facebook user in self.current_user

    The property is lazy-loaded on first access, using the cookie saved
    by the Facebook JavaScript SDK to determine the user ID of the active
    user. See http://developers.facebook.com/docs/authentication/ for
    more information.
    """
    @property
    def current_user(self):
        if self.session.get("user"):
            # User is logged in
            return self.session.get("user")
        else:
            # Either used just logged in or just saw the first page
            # We'll see here
            cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                   FACEBOOK_APP_ID,
                                                   FACEBOOK_APP_SECRET)
            if cookie:
                # Okay so user logged in.
                # Now, check to see if existing user
                user = User.get_by_id(cookie["uid"])
                if not user:
                    # Not an existing user so get user info
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    logging.info(profile["id"])
                    user = User(
                        id=str(profile["id"]),
                        name=profile["name"],
                        profile_url=profile["link"],
                        access_token=cookie["access_token"]
                    )
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()
                # User is now logged in
                self.session["user"] = dict(
                    name=user.name,
                    profile_url=user.profile_url,
                    id=user.id,
                    access_token=user.access_token
                )
                return self.session.get("user")
        return None

    def dispatch(self):
        """
        This snippet of code is taken from the webapp2 framework documentation.
        See more at
        http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html

        """
        self.session_store = sessions.get_store(request=self.request)
        try:
            webapp2.RequestHandler.dispatch(self)
        finally:
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        """
        This snippet of code is taken from the webapp2 framework documentation.
        See more at
        http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html

        """
        return self.session_store.get_session()


class HomeHandler(BaseHandler):
    def get(self):
        template = jinja_environment.get_template('main.html')
        self.response.out.write(template.render(dict(
            facebook_app_id=FACEBOOK_APP_ID,
            current_user=self.current_user,
            box_id=self.request.get('box_id')
        )))


class RegisterHandler(BaseHandler):
    def get(self):
        box_id = self.request.get('box_id')
        user_id = self.request.get('user_id')
        logging.info('Register Box %s with User %s'%(box_id, user_id))
        box_query = RPiBox.query(RPiBox.id==box_id)
        boxes = box_query.fetch(1)
        if len(boxes) > 0:
            if boxes[0].users.count(user_id) == 0:
                boxes[0].users.append(user_id)
                boxes[0].put()
        else:
            new_box = RPiBox(id=box_id, users=[user_id])
            new_box.put()
        self.redirect('/?box_id=%s'%box_id)


class LogoutHandler(BaseHandler):
    def get(self):
        if self.current_user is not None:
            self.session['user'] = None
        self.redirect('/')


jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__))
)


app = webapp2.WSGIApplication([
    ('/', HomeHandler),
    ('/register', RegisterHandler),
    ('/logout', LogoutHandler)
], config=config, debug=True)
